package com.neoCalf.neoCommon.utils;

import com.neoCalf.neoCommon.enums.ResultCode;
import com.neoCalf.neoCommon.exception.AuthException;
import com.neoCalf.neoCommon.redis.RedisTool;
import lombok.NoArgsConstructor;

import java.util.Random;


/**
 * 验证码生成器
 */
@NoArgsConstructor
public class CodeUtils {
    private RedisTool<String> redisTool;

    public CodeUtils(RedisTool<String> redisTool) {
        this.redisTool = redisTool;
    }

    private static final String[] placeholder = {"000000", "00000", "0000", "000", "00", "0", ""};

    public String generateCode(String key) {
        int hashCode = key.hashCode();
        int encryption = 20030902;
        long result = hashCode ^ encryption;
        long nowTime = System.currentTimeMillis();
        result = result ^ nowTime;
        result = result % 1000000;
        result = result < 0 ? -result : result;
        String r = String.valueOf(result);
        String code = placeholder[r.length()] + r;
        redisTool.setX(key, code, 120);
        return code;
    }

    public String generateCode2(String key, long expire) {
        String code = String.format("%06d", new Random().nextInt(999999));
        redisTool.setX(key, code, expire);
        return code;
    }

    public void verifyCode(String key, String code) {
        String storedCode = redisTool.get(key);
        if (!(storedCode != null && storedCode.equals(code))) {
            throw new AuthException(ResultCode.CODE_10017, "验证码错误");
        }
//        redisTool.delete(key);
    }

    public void removeCode(String key) {
        redisTool.delete(key);
    }
}
